local cmp_status_ok, cmp = pcall(require, "cmp")
if not cmp_status_ok then
	return
end

local snip_status_ok, luasnip = pcall(require, "luasnip")
if not snip_status_ok then
	return
end

require("luasnip.loaders.from_vscode").lazy_load()

-- 下面会用到这个函数
local check_backspace = function()
	local col = vim.fn.col "." - 1
	return col == 0 or vim.fn.getline("."):sub(col, col):match "%s"
end


cmp.setup({
	snippet = {
		expand = function(args)
			require('luasnip').lsp_expand(args.body)
		end,
	},
	mapping = cmp.mapping.preset.insert({
		['<C-b>'] = cmp.mapping.scroll_docs(-4),
		['<C-f>'] = cmp.mapping.scroll_docs(4),
		['<C-e>'] = cmp.mapping.abort(), -- 取消补全，esc也可以退出
		['<CR>'] = cmp.mapping.confirm({ select = true }),

		["<Tab>"] = cmp.mapping(function(fallback)
			if cmp.visible() then
				cmp.select_next_item()
			elseif luasnip.expandable() then
				luasnip.expand()
			elseif luasnip.expand_or_jumpable() then
				luasnip.expand_or_jump()
			elseif check_backspace() then
				fallback()
			else
				fallback()
			end
		end, {
			"i",
			"s",
		}),

		["<S-Tab>"] = cmp.mapping(function(fallback)
			if cmp.visible() then
				cmp.select_prev_item()
			elseif luasnip.jumpable(-1) then
				luasnip.jump(-1)
			else
				fallback()
			end
		end, {
			"i",
			"s",
		}),
	}),

	-- 这里重要
	sources = cmp.config.sources({
		{ name = 'nvim_lsp' },
		{ name = 'luasnip' },
		{ name = 'path' },
	}, {
		{ name = 'buffer' },
	})
})


-- local cmp_status_ok, cmp = pcall(require, "cmp")
-- if not cmp_status_ok then
-- 	return
-- end
--
-- -- 检查退格键函数
-- local check_backspace = function()
-- 	local col = vim.fn.col "." - 1
-- 	return col == 0 or vim.fn.getline("."):sub(col, col):match "%s"
-- end
--
-- -- 主 cmp 配置
-- cmp.setup({
-- 	mapping = cmp.mapping.preset.insert({
-- 		['<C-b>'] = cmp.mapping.scroll_docs(-4),
-- 		['<C-f>'] = cmp.mapping.scroll_docs(4),
-- 		['<C-e>'] = cmp.mapping.abort(), -- 取消补全，esc也可以退出
-- 		['<CR>'] = cmp.mapping.confirm({ select = true }),
--
-- 		["<Tab>"] = cmp.mapping(function(fallback)
-- 			if cmp.visible() then
-- 				cmp.select_next_item()
-- 			elseif check_backspace() then
-- 				fallback()
-- 			else
-- 				fallback()
-- 			end
-- 		end, {
-- 			"i",
-- 			"s",
-- 		}),
--
-- 		["<S-Tab>"] = cmp.mapping(function(fallback)
-- 			if cmp.visible() then
-- 				cmp.select_prev_item()
-- 			else
-- 				fallback()
-- 			end
-- 		end, {
-- 			"i",
-- 			"s",
-- 		}),
-- 	}),
--
-- 	sources = cmp.config.sources({
-- 		{ name = 'nvim_lsp', priority = 1000 }, -- 从 LSP 获取补全
-- 		{ name = 'path',     priority = 500 },
-- 	}, {
-- 		{ name = 'buffer', priority = 250 },
-- 	}),
--
-- 	formatting = {
-- 		format = function(entry, vim_item)
-- 			vim_item.menu = string.format('[%s]', entry.source.name)
-- 			return vim_item
-- 		end
-- 	}
-- })
--
-- -- Java 文件类型的特定配置
-- cmp.setup.filetype('java', {
-- 	sources = cmp.config.sources({
-- 		{ name = 'nvim_lsp', priority = 1000 }, -- LSP 最高优先级
-- 		{ name = 'path',     priority = 500 },
-- 	}, {
-- 		{ name = 'buffer', priority = 250 },
-- 	})
-- })
--
-- -- 命令行补全
-- cmp.setup.cmdline(':', {
-- 	mapping = cmp.mapping.preset.cmdline(),
-- 	sources = {
-- 		{ name = 'cmdline' }
-- 	}
-- })
--
-- -- 搜索补全
-- cmp.setup.cmdline('/', {
-- 	mapping = cmp.mapping.preset.cmdline(),
-- 	sources = {
-- 		{ name = 'buffer' }
-- 	}
-- })
--
-- -- 补全状态检查命令
-- vim.api.nvim_create_user_command('CheckCompletion', function()
-- 	local clients = vim.lsp.get_active_clients()
-- 	local jdtls_found = false
--
-- 	for _, client in ipairs(clients) do
-- 		if client.name == 'jdtls' then
-- 			jdtls_found = true
-- 			print("✅ jdtls 客户端: " .. (client.initialized and "已初始化" or "未初始化"))
-- 			break
-- 		end
-- 	end
--
-- 	if not jdtls_found then
-- 		print("❌ jdtls 客户端未找到")
-- 	end
--
-- 	-- 检查 cmp 状态
-- 	print("ℹ️  使用 :CmpStatus 查看详细补全状态")
-- end, {})
--
-- -- 自动补全触发优化
-- vim.api.nvim_create_autocmd('InsertEnter', {
-- 	pattern = '*.java',
-- 	callback = function()
-- 		-- 确保 LSP 客户端活跃
-- 		local clients = vim.lsp.get_active_clients()
-- 		for _, client in ipairs(clients) do
-- 			if client.name == 'jdtls' and not client.initialized then
-- 				vim.defer_fn(function()
-- 					vim.notify("🔄 初始化 jdtls 补全功能...", vim.log.levels.INFO)
-- 				end, 100)
-- 			end
-- 		end
-- 	end
-- })
